package com.github.icloudpay.pay.core.service.refund.wechat.service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.github.icloudpay.pay.core.feign.PayChannelConfigFeign;
import com.github.icloudpay.pay.core.service.refund.RefundCallbackService;
import com.github.icloudpay.pay.core.util.AESUtils;
import com.github.wxiaoqi.security.common.admin.pay.request.CallbackRequest;
import com.github.wxiaoqi.security.common.admin.pay.response.WechatCallbackReponse;
import com.github.wxiaoqi.security.common.util.Base64Utils;
import com.github.wxiaoqi.security.common.util.MD5;
import com.github.wxiaoqi.security.common.util.Utils;

/**
 * 微信退款回调
 * @author hexufeng
 *
 */
@Service("wechatRefundCallBackService")
public class WechatRefundCallBackService {

	private static final Logger logger = (Logger) LoggerFactory.getLogger(WechatRefundCallBackService.class);
 
	@Autowired
	private PayChannelConfigFeign payChannelConfigFeign;
	@Autowired
	private RefundCallbackService refundCallbackService;
 
	public WechatCallbackReponse refundBack(Map<String, Object> request){

		WechatCallbackReponse callbackReponse = new WechatCallbackReponse();

		String return_code = (String) request.get("return_code");

		if(!"SUCCESS".equals(return_code)){
			logger.error("微信退款回调通知结果失败");
			callbackReponse.setReturn_code("FAIL");
			return callbackReponse;
		}

		String appid = (String) request.get("appid");//appid
		String mch_id = (String) request.get("mch_id");//微信商户号
		String req_info = (String) request.get("req_info");//加密信息

		//根据微信商户号和appid查询支付通道密钥
		Map<String, Object> reqMap = new HashMap<String, Object>();
    	reqMap.put("outMerNo", mch_id);
    	reqMap.put("outMerAccount", appid);
		Map<String, Object> respMap = payChannelConfigFeign.queryByOutMerNo(reqMap);
        if(!(boolean) respMap.get("success")){
			logger.error("微信退款回调通知支付通道为空");
			callbackReponse.setReturn_code("FAIL");
			return callbackReponse;
		}
        
        @SuppressWarnings("unchecked")
		Map<String, Object> configMap = (Map<String, Object>)respMap.get("payChannelConfigInfo");

		String outMerKey = (String) configMap.get("outMerKey");//MD5加密key
		//参数密文解密
		String md5 = MD5.md5(outMerKey);//对商户密钥进行MD5
		byte[] keyBytes = Base64Utils.decode(req_info);//对加密串做base64解码
		String reqInfo = "";
		try {
			reqInfo = AESUtils.aesDecryptByBytes(keyBytes, md5);//对加密串进行AES解密
		} catch (Exception e) {
			e.printStackTrace();
			callbackReponse.setReturn_code("FAIL");
			return callbackReponse;
		}

		JSONObject jsonPayOrderObject = (JSONObject) JSONObject.parse(reqInfo);
		String out_refund_no = (String) jsonPayOrderObject.get("out_refund_no");
		String transaction_id = (String) jsonPayOrderObject.get("transaction_id");
		String total_fee = Utils.changeToYuan(ObjectUtils.toString(request.get("total_fee")));
		CallbackRequest callbackRequest = new CallbackRequest();
		callbackRequest.setRequestNo(out_refund_no);
		callbackRequest.setOrderAmt(new BigDecimal(total_fee));
		callbackRequest.setRemoteTxJournalNo(transaction_id);

		if("SUCCESS".equals(request.get("result_code"))){
			//验证成功
			callbackRequest.setStatus("00");
			refundCallbackService.callBack(callbackRequest);
		}else {
			logger.info("微信支付回调状态{},不做处理",request.get("result_code"));
			callbackRequest.setStatus("01");
			refundCallbackService.callBack(callbackRequest);
		}
		callbackReponse.setReturn_code("SUCCESS");
		return callbackReponse;
	}

}
